package com.bdqn.service.serviceImpl;

import bean.User;
import com.bdqn.common.utils.EncryptUtil;
import com.bdqn.dao.UserDao;
import com.bdqn.service.UserSevice;
import com.bdqn.service.utils.SecurityConstant;
import io.jsonwebtoken.Jwts;

import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserServiceImpl implements UserSevice {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private UserDao userDao;
    @Override
    public Map<Object,Object> find(String moblie, String password) throws JSONException {
        User member = userDao.find(moblie);
        //登陆成功生成JWT
        String token = Jwts.builder()
                //主题 放入用户名
                .setSubject(SecurityConstant.ACCOUNT_MEMBER_SPLIT + moblie)
                //自定义属性 放入用户拥有请求权限
                .claim(SecurityConstant.AUTHORITIES, "[]")
                //失效时间
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))
                //签名算法和密钥
                .signWith(SignatureAlgorithm.HS512, SecurityConstant.JWT_SIGN_KEY)
                .compact();
        token = SecurityConstant.TOKEN_SPLIT + token;

        Map<Object,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("member", member);
        return map;
    }

    @Override
    public User select_find(String phone) {
        return userDao.find(phone);
    }

    @Override
    public User Login_find(String moblie,String password) {
        return userDao.Login_find(moblie,EncryptUtil.md5(password));
    }
    //校验手机号是否被注册
    @Override
    public Integer phone(String phone) {
        return userDao.phone(phone);
    }
    //校验是否含有该邀请码
    @Override
    public String Invitationcode(String Invitation) {
        return userDao.invitationcode(Invitation);
    }

    //检查有没有该邮箱
    @Override
    public Integer Email(String email) {
        return userDao.Email(email);
    }

    //校验邮箱是否是该手机号
    @Override
    public String QueryEmail(String phone) {
        return userDao.QueryeEail(phone);
    }

    //注册
    @Override
    public void register(String moblie, String password,String Code,String email) {//需要加密
        //EncryptUtil.md5
        String pass = EncryptUtil.md5(password);
        userDao.register(moblie,pass,Code,email);
    }

    @Override
    public Integer forget(String password, String phone) {
        return userDao.forget(EncryptUtil.md5(password),phone);
    }
}